from fastapi import Depends, HTTPException, status, Request
from fastapi.security import HTTPBearer
from sqlalchemy.orm import Session, joinedload

from server.controller.check_token import check_token

from server.db.models.system import User, Role
from server.etc.database import create_db

security = HTTPBearer()


def get_user_info(query_set):
    user_data = dict()
    for query in query_set:
        # 构建用户基本信息
        user_data.update({
            "id": query.id,
            "username": query.username,
            "real_name": query.real_name,
            "phone": query.phone,
            "is_active": query.is_active,
            "is_superuser": query.is_superuser,
            "avatar": query.avatar,
            "role_list": []
        })

        # 处理每个权限及其关联菜单
        for role in query.roles:
            role_data = {
                "id": role.id,
                "name": role.name,
                "code": role.code,
                "description": role.description,
                "menu_list": [{
                    "name": menu.name,
                    "path": menu.path,
                    "icon": menu.icon,
                    "order": menu.order,
                    "permission": menu.permission,
                } for menu in role.menus]
            }
            user_data["role_list"].append(role_data)

    return user_data



def check_permission(required_permission: str):
    def _check_permission(
            request: Request,
            db: Session = Depends(create_db)
    ):
        # 1. 验证Token
        current_user = check_token(request),
        if isinstance(current_user, dict):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail=current_user["msg"],
                headers={"WWW-Authenticate": "Bearer"},
            )
        else:
            user_id = current_user[0]

            # 2. 获取用户权限
            user_infos = db.query(User).options(
                joinedload(User.roles).joinedload(Role.menus)
            ).filter(
                User.id == user_id,
            ).all()

            user_data = get_user_info(user_infos)
            # 3. 超级管理员拥有所有权限
            if user_data["is_superuser"]:
                return user_id

            # 4. 检查权限
            if required_permission not in str(user_data["role_list"]):
                raise HTTPException(
                    status_code=status.HTTP_403_FORBIDDEN,
                    detail="没有访问权限"
                )

            return user_id

        # user_id = current_user[0]
        #
        # # 2. 获取用户权限
        # user_infos = db.query(User).options(
        #     joinedload(User.roles).joinedload(Role.menus)
        # ).filter(
        #     User.id == user_id,
        # ).all()
        #
        # user_data = get_user_info(user_infos)
        # # 3. 超级管理员拥有所有权限
        # if user_data["is_superuser"]:
        #     return user_id
        #
        # # 4. 检查权限
        # if required_permission not in str(user_data["role_list"]):
        #     raise HTTPException(
        #         status_code=status.HTTP_403_FORBIDDEN,
        #         detail="没有访问权限"
        #     )
        #
        # return user_id

    return _check_permission

# def check_permission(
#         required_permission: str,
#         current_user: str = Depends(check_token),
#         db: Session = Depends(create_db)
# ) -> any:
#     # 1. 验证Token
#
#     # 如果返回的是字典，说明验证失败
#     if isinstance(current_user, dict):
#         raise HTTPException(
#             status_code=status.HTTP_401_UNAUTHORIZED,
#             detail=current_user["msg"],
#             headers={"WWW-Authenticate": "Bearer"},
#         )
#
#     # 验证成功，可以继续查询用户信息
#     user_id = current_user
#     # 2. 获取用户权限
#     user_infos = db.query(User).options(
#         joinedload(User.roles).joinedload(Role.menus)
#     ).filter(
#         User.id == user_id,
#     ).all()
#
#     user_data = get_user_info(user_infos)
#     # 3. 超级管理员拥有所有权限
#     if user_data["is_superuser"]:
#         return True
#
#     # 4. 检查权限
#     if required_permission not in  str({user_data["role_list"]}):
#         raise HTTPException(
#             status_code=status.HTTP_403_FORBIDDEN,
#             detail="没有访问权限"
#         )
#
#     return True